<template>
  <div>
    <el-form ref="form" :model="form" label-width="80px" inline size="mini">
      <el-form-item label="用户名">
        <el-input
          clearable
          v-model="form.username"
          placeholder="请输入账户"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号码">
        <el-input
          clearable
          v-model="form.phoneNumber"
          placeholder="请输入手机号码"
        ></el-input>
      </el-form-item>

      <el-form-item label="状态">
        <el-select v-model="form.status" placeholder="请选择状态" clearable>
          <el-option label="启动" value="0"></el-option>
          <el-option label="禁用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="el-icon-search" @click="searchRole"
          >查询</el-button
        >
        <el-button
          type="success"
          class="el-icon-folder-add"
          @click="saveOrUpdateUser('add')"
          >新增用户</el-button
        >
        <el-button
          type="danger"
          icon="el-icon-delete"
          @click="allDelet"
          :disabled="ids.length == 0"
          >批量删除</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      :data="tableList"
      border
      style="width: 100%"
      @select="selectUser"
      @select-all="selectAllUser"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column width="60" align="center" type="index" label="序号">
      </el-table-column>
      <el-table-column
        width="100"
        header-align="center"
        align="center"
        prop="username"
        label="用户名"
      >
      </el-table-column>
      <el-table-column
        width="100"
        header-align="center"
        align="center"
        prop="nickName"
        label="昵称"
      >
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        prop="phoneNumber"
        label="手机号"
      >
      </el-table-column>
      <el-table-column header-align="center" align="center" label="权限列表">
        <template slot-scope="{ row }">
          <el-tag size="medium" v-for="item in row.sysRoleList" :key="item.id">
            {{ item.name }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        prop="createTime"
        label="创建时间"
      >
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        prop="updateTime"
        label="更新时间"
      >
      </el-table-column>
      <el-table-column header-align="center" align="center" label="状态">
        <template slot-scope="{ row }">
          <el-switch
            :value="row.status"
            active-value="0"
            inactive-value="1"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="switchChange(row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{ row }">
          <el-button
            type="text"
            class="el-icon-edit"
            @click="saveOrUpdateUser('edit', row)"
            >修改</el-button
          >
          <el-button
            type="text"
            class="el-icon-delete"
            slot="reference"
            @click="deleteUser(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
      <!-- 无数据 -->
      <template slot="empty">
        <div class="noData" v-show="tableList.length === 0">
          <img src="@/assets/images/noData.png" />
          <p>暂无数据</p>
        </div>
      </template>
    </el-table>
    <Pagination :total="total" @pagination="handleSizeChange" :page.sync="form.pageNum"></Pagination>

    <el-dialog :title="flag" :visible.sync="dialogVisible" width="600px">
      <el-form
        ref="userForm"
        :model="userForm"
        :rules="rules"
        inline
        size="mini"
        label-width="80px"
      >
        <el-row>
          <el-col :span="12"
            ><el-form-item label="用户名" prop="username">
              <el-input
                v-model="userForm.username"
                placeholder="请输入账户名称"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickName">
              <el-input
                v-model="userForm.nickName"
                placeholder="请输入用户昵称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="flag == '新增用户'">
            <el-form-item label="账户密码" prop="password">
              <el-input
                v-model="userForm.password"
                placeholder="请输入账户密码"
              ></el-input> </el-form-item
          ></el-col>

          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input
                v-model="userForm.phoneNumber"
                placeholder="请输入手机号码"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="userForm.email"
                placeholder="请输入邮箱地址"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联角色">
              <!-- @remove-tag="removeTag" -->
              <el-select
                v-model="userForm.sysRoleIds"
                placeholder="请选择"
                multiple
              >
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="item in allSysRoleList"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-radio v-model="userForm.sex" label="1">男</el-radio>
              <el-radio v-model="userForm.sex" label="0">女</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户状态">
              <el-switch
                v-model="userForm.status"
                active-value="0"
                inactive-value="1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { roleList } from "@/api/system-setup/role-management";
import {
  updateUserPwd,
  userList,
  saveAndUpdate,
  updateStatus,
  deleteUser,
  grantRole,
} from "@/api/system-setup/user-management";
export default {
  data() {
    return {
      ids: [],
      flag: "",
      total: 0,
      dialogVisible: false,
      form: {
        username: "",
        phoneNumber: "",
        status: "",
        pageNum: 0,
        pageSize: 10,
      },
      userForm: {
        avatar: "",
        username: "",
        nickName: "",
        password: "",
        phoneNumber: "",
        email: "",
        sex: "1",
        status: "0",
        sysRoleIds: [],
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" },
        ],
        nickName: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
            message: "请输入正确的邮箱格式",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 11,
            message: "长度在 6 到 11 个字符",
            trigger: "blur",
          },
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            pattern: /^1[3|5|7|8|9]\d{9}$/,
            message: "请输入正确的号码格式",
            trigger: "blur",
          },
        ],
      },
      tableList: [],
      allSysRoleList: [],
      initForm: {},
    };
  },
  created() {
    this.initForm = this.$cloneDeep(this.userForm);
    this.getRolesInfo();
    this.getTableData();
  },
  methods: {
    async getRolesInfo() {
      let data = {
        code: "",
        id: 0,
        name: "",
        pageNum: 1, //当前页
        pageSize: 9999, //每页条数
        remark: "", //备注
      };
      let res = await roleList(data);
      if (res.code === 200) {
        this.allSysRoleList = res.data.records;
      }
    },
    async getTableData(data = this.form) {
      let res = await userList(data);
      if (res.code == 200) {
        this.tableList = res.data.userList.records;
        this.total = res.data.userList.total;
      }
    },

    //查询
    searchRole() {
      this.form.pageNum = 1;
      this.getTableData();
    },
    //添加或修改
    saveOrUpdateUser(type, row) {
      console.log(row);

      this.dialogVisible = true;
      if (type == "add") {
        this.flag = "新增用户";
        this.userForm = this.$cloneDeep(this.initForm);
        this.$nextTick(() => {
          this.$refs.userForm.clearValidate();
        });
      } else {
        this.flag = "修改用户";
        this.userForm = Object.assign(this.userForm, this.$cloneDeep(row));
        this.userForm.sysRoleIds = [];
        row.sysRoleList.forEach((item, index) => {
          this.userForm.sysRoleIds.push(item.id);
        });
      }
    },
    selectUser(selection, row) {
      let index = this.ids.indexOf(row.id);
      index === -1 ? this.ids.push(row.id) : this.ids.splice(index, 1);
    },
    selectAllUser(selection) {
      this.ids = [];
      selection.forEach((item) => {
        this.ids.push(item.id);
      });
    },
    allDelet() {
      this.$confirm("是否删除选中的用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await deleteUser(this.ids);
          if (res.code == 200) {
            this.tableList.length > 1 ? this.form.pageNum : this.form.pageNum--;
            this.getTableData();
            this.ids = [];
          }
        })
        .catch(() => {
          this.$message("已取消");
        });
    },
    //启用或禁用
    switchChange(row) {
      let text = row.status === "0" ? "禁用" : "启用";
      this.$confirm(`是否${text}该用户`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let status = text === "禁用" ? "1" : "0";
          let res = await updateStatus({ id: row.id, status });
          if (res.code == 200) {
            this.getTableData();
          }
        })
        .catch(() => {
          //this.$message("取消");
        });
    },
    deleteUser({ id, username }) {
      this.$alert(`此操作将永久删除用户：“${username}”，是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        showCancelButton: true,
      })
        .then(async () => {
          let res = await deleteUser([id]);
          if (res.code == 200) {
            this.tableList.length > 1 ? this.form.pageNum : this.form.pageNum--;
            this.getTableData();
          }
        })
        .catch(() => {});
    },
    handleSizeChange(val) {
      this.form.pageNum = val.page;
      this.form.pageSize = val.limit;
      this.getTableData();
    },
    confirm() {
      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          if (this.flag == "修改用户") {
            let res1 = await grantRole({
              data: this.userForm.sysRoleIds,
              userId: this.userForm.id,
            });
          }

          let res2 = await saveAndUpdate(this.userForm);
          // if (res.code == 200) {
          //   console.log(res);
          //   this.getTableData();
          // }
          //  let res = Promise.all([res1,res2])
          if (res2.code == 200) {
            this.getTableData();
            this.dialogVisible = false;
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scope></style>
